package com.hilinos.ftp.core;

import com.hilinos.ftp.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.DbUserManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 注意：被@Configuration标记的类会被加入ioc容器中，而且类中所有带 @Bean注解的方法都会被动态代理，因此调用该方法返回的都是同一个实例。
 * ftp服务访问地址：
 * ftp://localhost:3131/
 */
@Slf4j
@Configuration("MyFtp")
public class MyFtpServer {

    @Autowired
    private MyFtplet myFtplet;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private UserManager userManager;

    protected FtpServer server;

    //我们这里利用spring加载@Configuration的特性来完成ftp server的初始化
    public MyFtpServer() {
        log.info("Apache ftp server is already instantiation complete!");
    }

    /**
     * ftp server init
     *
     * @throws IOException
     */
    public void initFtp() {
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory listenerFactory = new ListenerFactory();
        // 设置服务端口
        listenerFactory.setPort(serverConfig.getPort());
        // 设置被动模式数据上传的接口范围,云服务器需要开放对应区间的端口给客户端
        DataConnectionConfigurationFactory dataConnectionConfFactory = new DataConnectionConfigurationFactory();
        dataConnectionConfFactory.setPassivePorts(serverConfig.getPassivePorts());
        listenerFactory.setDataConnectionConfiguration(dataConnectionConfFactory.createDataConnectionConfiguration());
        // 替换默认的监听器
        Listener listener = listenerFactory.createListener();
        serverFactory.addListener("default", listener);
        // 设置ftp监听
        Map<String, Ftplet> m = new HashMap<>();
        m.put("miaFtplet", myFtplet);
        serverFactory.setFtplets(m);
        // 基于数据库来存储用户实例
        serverFactory.setUserManager(userManager);
        // 实例化FTP Server
        server = serverFactory.createServer();
    }


    /**
     * ftp server start
     */
    public void start() {
        try {
            initFtp();
            server.start();
            log.info("Apache Ftp server is starting!");
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

}